import time
import datetime
from core.tools.custom_requests import CustomRequests
from .base import CzbApiBase
from core.wchat.wx_base import mc
from finance_c2c.local_settings import ONLINE


class CzbApi(CustomRequests, CzbApiBase):
    def __init__(self, czb_app_secret, czb_channelId, czb_key, czb_payCode):
        """
        :param czb_app_secret:
        :param czb_channelId:
        :param czb_key:
        :param czb_payCode:
        """
        self.app_secret = czb_app_secret
        self.channelId = czb_channelId
        self.key = czb_key
        self.payCode = czb_payCode
        self.mc = mc

    # 获取车主邦加油站信息保存到本地
    def query_gas_info_list(self):
        if ONLINE:
            base_url = "https://mcs.czb365.com/services/v3/gas/queryGasInfoListOilNoNew"
        else:
            base_url = "https://test-mcs.czb365.com/services/v3/gas/queryGasInfoListOilNoNew"
        parameters = {
            "channelId": self.channelId,
            "timestamp": str(time.time()).replace(".", "")[:13],
            "app_key": self.key
        }
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        response = self.get(base_url, params=parameters)
        return response

    # 获取token
    def get_token_from_mc(self, tel):
        token_key = self.get_token_key(self.key + tel)
        if not self.mc.get(token_key):
            response = self.platform_login(tel)
            result = response.get("result")
            token = result.get("token")
            return token
        else:
            token = self.mc.get(token_key)
            return token

    # 用户登录
    def platform_login(self, tel):
        if ONLINE:
            base_url = "https://mcs.czb365.com/services/v3/begin/platformLoginSimpleAppV4"
        else:
            base_url = "https://test-mcs.czb365.com/services/v3/begin/platformLoginSimpleAppV4"
        parameters = {
            "platformType": self.channelId,
            "platformCode": tel,
            "timestamp": str(time.time()).replace(".", "")[:13],
            "app_key": self.key
        }
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        response = self.post(base_url, data=parameters)
        token_key = self.get_token_key(tel)
        result = response.get("result")
        token = result.get("token")
        self.mc.set(token_key, token, 60 * 60 * 24 * 20)
        return response

    # h5支付获取支付链接
    def get_pay_url(self, tel, gasId, gunNo):
        """
        :param tel: 手机号
        :param gasId: 油站
        :param gunNo: 油枪
        :return:
        """
        base_url = "https://test-open.czb365.com"
        format_str = {"base_url": base_url, "platformType": self.channelId, "platformCode": tel, "gasId": gasId,
                      "gunNo": gunNo}
        url = "{base_url}/redirection/todo/?platformType={platformType}&platformCode={platformCode}&gasId={gasId}&gunNo={gunNo}".format(
            **format_str)
        return url

    #  根据用户查询油站状态和油价
    def query_price_by_phone(self, gasIds, phone, channel=None):
        if ONLINE:
            base_url = "https://mcs.czb365.com/services/v3/gas/queryPriceByPhone"
        else:
            base_url = "https://test-mcs.czb365.com/services/v3/gas/queryPriceByPhone"
        parameters = {
            "platformType": self.channelId,
            "timestamp": str(time.time()).replace(".", "")[:13],
            "app_key": self.key,
            "phone": phone,
            "gasIds": gasIds
        }
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        response = self.post(base_url, data=parameters)
        result = response.get("result")
        response["result"] = result
        return response

    # 提交订单
    def generate_order(self, gasId, gunNo, amountGun, outerOrderId, priceGun, priceUnit, litre, token):
        """
        :param gasId: 油站id
        :param gunNo: 抢号
        :param amountGun:  用户输入价格
        :param outerOrderId: 外部单号
        :param priceGun: 枪价
        :param priceUnit: 下单时享有价格
        :param litre:
        :param token: 车主邦用户token
        升数 = amountGun(订单总金额) / priceGun(下单时实时枪价)
        实付 = 升数 * priceUnit（下单时享有单价）
        优惠金额 = amountGun - 实付
        :return:
        """
        if ONLINE:
            base_url = "https://mcs.czb365.com/services/v3/orderws/generateOrder"
        else:
            base_url = "https://test-mcs.czb365.com/services/v3/orderws/generateOrder"
        parameters = {
            "app_key": self.key,
            "timestamp": str(time.time()).replace(".", "")[:13],
            "gunNo": str(gunNo),
            "gasId": gasId,
            "amountGun": str(amountGun),
            "priceGun": str(priceGun),
            "priceUnit": str(priceUnit),
            "litre": str(litre),
            "outerOrderId": outerOrderId,
            "token": token,
        }
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        print(parameters, "提交订单请求参数")
        response = self.post(base_url, data=parameters)
        print(response, "提交订单返回参数")
        print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        return response

    # 取消订单
    def cancel_order(self, orderId, token=None):
        """
        :param orderId: 车主邦orderId
        :param token: 车主邦orderId
        :return:
        """
        if ONLINE:
            base_url = "https://mcs.czb365.com/services/v3/orderws/cancelOrder"
        else:
            base_url = "https://test-mcs.czb365.com/services/v3/orderws/cancelOrder"
        parameters = {
            "timestamp": str(time.time()).replace(".", "")[:13],
            "app_key": self.key,
            "orderId": orderId,
            "token": token
        }
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        response = self.post(base_url, data=parameters)
        return response

    # 支付接口（下单）
    def order_pay(self, orderSn, payAmount, payStatus, token):
        if ONLINE:
            base_url = "https://mcs.czb365.com/services/v3/payCallback"
        else:
            base_url = "https://test-mcs.czb365.com/services/v3/payCallback"
        parameters = {
            "payCode": self.payCode,  # 支付编码 联调时由车主邦指定
            "timestamp": str(time.time()).replace(".", "")[:13],
            "app_key": self.key,
            "orderSn": orderSn,
            "payAmount": str(payAmount),
            "payStatus": str(payStatus),
            "token": token,
        }
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        print(parameters, "支付接口请求参数")
        response = self.post(base_url, data=parameters)
        print(response, "支付接口返回参数")
        return response

    # 退款接口
    def order_refund(self, orderSn, payAmount, outOrderId, token):
        if ONLINE:
            base_url = "https://mcs.czb365.com/services/v3/orderws/applyRefund"
        else:
            base_url = "https://test-mcs.czb365.com/services/v3/orderws/applyRefund"
        parameters = {
            "app_key": self.key,
            "timestamp": str(time.time()).replace(".", "")[:13],
            "orderSn": orderSn,
            "refundAmount": str(payAmount),
            "outOrderId": outOrderId,
            "token": token,
        }
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        print(parameters, "申请退款请求参数")
        response = self.post(base_url, data=parameters)
        print(response, "申请退款返回参数")
        return response

    # 订单查询
    def query_order(self, orderId):
        if ONLINE:
            base_url = "https://mcs.czb365.com/services/v3/orderws/platformOrderQuery"
        else:
            base_url = "https://test-mcs.czb365.com/services/v3/orderws/platformOrderQuery"
        parameters = {
            "orderSource": self.channelId,
            "app_key": self.key,
            "timestamp": str(time.time()).replace(".", "")[:13],
            "orderId": orderId,
        }
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        print(parameters, "订单查询请求参数")
        response = self.post(base_url, data=parameters)
        print(response, "订单查询返回参数")
        return response

    # 查询直降金额
    def query_depreciate_amount(self, gasId, oilNo, amountGun, phone):
        if ONLINE:
            base_url = "https://mcs.czb365.com/services/v3/gas/queryDepreciateAmount"
        else:
            base_url = "https://test-mcs.czb365.com/services/v3/gas/queryDepreciateAmount"
        parameters = {
            "orderSource": self.channelId,
            "app_key": self.key,
            "timestamp": str(time.time()).replace(".", "")[:13],
            "phone": phone,
            "platform": self.channelId,
            "gasId": gasId,
            "oilNo": oilNo,
            "amountGun": amountGun,
        }
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        response = self.post(base_url, data=parameters)
        return response

    # 创建订单(使用车主邦直降活动提交数据)
    def create_orders(self, gasId, gunNo, amountGun, outerOrderID, token, couponId=-1):
        if ONLINE:
            base_url = "https://mcs.czb365.com/services/v3/orderws/createOrder"
        else:
            base_url = "https://test-mcs.czb365.com/services/v3/orderws/createOrder"
        parameters = {
            "orderSource": self.channelId,
            "app_key": self.key,
            "timestamp": str(time.time()).replace(".", "")[:13],
            "platform": self.channelId,
            "gasId": gasId,
            "gunNo": gunNo,
            "amountGun": amountGun,
            "outerOrderID": outerOrderID,
            "couponId": couponId,
            "token": token
        }
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        print(parameters, "创建订单(使用车主邦直降活动提交数据)")
        response = self.post(base_url, data=parameters)
        print(response, "创建订单,使用车主邦直降活动提交数据 返回数据")
        return response

    # 订单开票
    def gas_insert(self, token, **kwargs):
        """
        title Integer 是 0 公司 1 个人
        buyerTaxNo String 否 购方纳税人识别号,公司开票时不能为空
        buyerName String 是 购方单位名称
        buyerAddressPhone String 否 购方地址及电话
        buyerBankAccount String 否 购方开户行及账号
        buyerEmail String 是 购方客户邮箱
        orders String 是 订单号以字符串分割
        invoiceContent Integer 是 开票类型 1:油票
        orderSource String 是 渠道编码，对接时⻋主邦提供
        :return:
        """
        if ONLINE:
            base_url = "https://mcs.czb365.com/services/v3/invoiceThird/gasInsert"
        else:
            base_url = "https://test-mcs.czb365.com/services/v3/invoiceThird/gasInsert"
        parameters = {
            "orderSource": self.channelId,
            "app_key": self.key,
            "timestamp": str(time.time()).replace(".", "")[:13],
            "platform": self.channelId,
            "title": kwargs.get("title"),
            "buyerName": kwargs.get("buyerName"),
            "buyerEmail": kwargs.get("buyerEmail"),
            "orders": kwargs.get("orderId"),
            "invoiceContent": 1,
            "buyerBankAccount": kwargs.get("buyerBankAccount"),
            "buyerAddressPhone": kwargs.get("buyerAddressPhone"),
            "buyerTaxNo": kwargs.get("buyerTaxNo"),
            "token": token,
        }
        if kwargs.get("title") == 1:
            del parameters["buyerTaxNo"]
            del parameters["buyerBankAccount"]
        parameters = self.delete_none(**parameters)
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        print(parameters, "订单开票 提交数据")
        response = self.post(base_url, data=parameters)
        print(response, "订单开票返回数据")
        return response

    # 查询开票信息
    def queryInvoiceListWithPage(self, token, **kwargs):
        if ONLINE:
            base_url = "https://mcs.czb365.com/services/v3/invoice/queryInvoiceListWithPage"
        else:
            base_url = "https://test-mcs.czb365.com/services/v3/invoice/queryInvoiceListWithPage"
        parameters = {
            "app_key": self.key,
            "timestamp": str(time.time()).replace(".", "")[:13],
            "platform": self.channelId,
            "pageSize": kwargs.get("pageSize"),
            "pageIndex": kwargs.get("pageIndex"),
            "orderSource": self.channelId,
            "token": token,
        }
        parameters = self.delete_none(**parameters)
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        print(parameters, "查询开票")
        response = self.post(base_url, data=parameters)
        print(response, "查询开票 返回结果")
        return response


def get_czb_api(channel_key):
    from .models import ChannelRiseInPrice
    print(channel_key, "channel_key")
    czb_channel_instance = ChannelRiseInPrice.objects.get(channel__app_key=channel_key)
    czb_api = CzbApi(czb_channel_instance.czb_app_secret, czb_channel_instance.czb_channelId,
                     czb_channel_instance.czb_key,
                     czb_channel_instance.czb_payCode)
    return czb_api


def get_czb_api_by_czb_appkey(czb_appkey):
    from .models import ChannelRiseInPrice
    czb_channel_instance = ChannelRiseInPrice.objects.filter(czb_key=czb_appkey).first()
    czb_api = CzbApi(czb_channel_instance.czb_app_secret, czb_channel_instance.czb_channelId,
                     czb_channel_instance.czb_key,
                     czb_channel_instance.czb_payCode)
    return czb_api
